package com.wuercloud.mq.config;

import com.wuercloud.mq.message.converter.FastJsonMessageConverter;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by JiangWL on 2017/3/21.
 */
@Component
public class RabbitMqInInitializer {
    private Map<String,RabbitTemplate> templateMap = new ConcurrentHashMap<>();



    @Autowired
    private RestTemplate restClientTemplate;
    @Autowired
    private ConnectionFactory rabbitConnectionFactory;
    @Autowired
    private FastJsonMessageConverter fastJsonMessageConverter;

    @PostConstruct
    void init(){
        System.out.println("初始队列配置内容。。。");
        final List<String> bindKeyStrList = getMqConfigList();
        initRabbitTemplateMap(bindKeyStrList);
    }

    private void initRabbitTemplateMap(final List<String> bindKeyStrList) {
        bindKeyStrList.stream().forEach(bindKey ->setTempalte(bindKey));
    }
    public void setTempalte(final String bindKey){
        if (!this.templateMap.containsKey(bindKey)){
            RabbitTemplate template = new RabbitTemplate(rabbitConnectionFactory);
            template.setExchange("520WAWA-".concat(bindKey.substring(0,bindKey.lastIndexOf("-"))));
            template.setRoutingKey(bindKey);
            template.setMandatory(true);
            //截取520wawa-以后的
            template.setQueue(bindKey);
            template.setMessageConverter(fastJsonMessageConverter);
            //采用Mandatory，故此处不用
            //template.setRetryTemplate(retryTemplate);
            this.templateMap.put(bindKey,template);

        }

    }
    /**
     * 根据映射配置KEY生成RabbitTemplate信息
     * 信息管理系统ISMP增加映射时调用
     * @param bindKey
     */
    private void insertTemplate(String bindKey){
        setTempalte(bindKey);
    }


    public Map<String, RabbitTemplate> getTemplateMap() {
        if (this.templateMap==null || this.templateMap.isEmpty()){
            initRabbitTemplateMap(getMqConfigList());
        }
        return this.templateMap;
    }


    /**
     * 获取队列映射配置信息列表
     * @return
     */
    public List<String> getMqConfigList(){
        //获取REST服务地址返回的对象
        //this.restClientTemplate.postForObject("http://localhost:8080/ismp/config/all",null,null);
        //获取配置映射信息List,此处构建模拟的空内容,后面获取真实信息，REST数据接口或DB读取
        return Arrays.asList(new String[]{"SMS-DOOR-ZHOUSHAN","SMS-DOOR-YFKJ"});
    }
}
